package com.gitee.zhuyb.richtext.word;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @version 1.0.0
 * @Description: #类描述
 * @Date: 2022/1/16 13:57
 * @Copyright (C) ZhuYouBin
 */
@RestController
@RequestMapping("/export")
public class ExportController {

    @RequestMapping(value = "/exportWord")
    public void export(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            // TODO 从文件中读取测试数据
            StringBuffer tmpContent = new StringBuffer();
            String fileName = "G:\\zhuyoubin_gitee_space\\code\\work-demo\\poi-word\\src\\main\\resources\\image_base64.txt";
            try (Scanner sc = new Scanner(new FileReader(fileName))) {
                while (sc.hasNextLine()) {  //按行读取字符串
                    String line = sc.nextLine();
                    tmpContent.append(line);
                }
            }
            String content = tmpContent.toString();

            // 获取img图片标签
            // 1.Jsoup解析html
            Document document = Jsoup.parse(content);
            // 获取所有img图片标签
            Elements img = document.getElementsByTag("img");
            int index = 0;
            List<String> imgBase64List = new ArrayList<>();
            for (Element element : img) {
                imgBase64List.add(element.attr("src"));
                // 处理特殊符号
                String attrData = element.attr("src");
                // base64编码后可能包含 + 特殊字符,所以需要转义
                attrData = attrData.replaceAll("\\+", "\\\\+");
                content = content.replaceAll(attrData, "{{image_src" + index + "}}");
                index++;
            }
            // 缩放图片大小,然后重新base64编码后替换到富文本内容里面导出word
            index = 0;
            for (String base64 : imgBase64List) {
                if (StringUtils.isNotBlank(base64)) {
                    int endIndex = base64.indexOf("base64,");
                    String prefix = base64.substring(0, endIndex + "base64,".length()); // "data:image/png;base64,"; // base64编码前缀
                    // 缩小图片
                    base64 = base64.replaceAll(prefix, "");
                    BufferedImage bufferedImage = ImageUtils.bytesToBufferedImage(ImageUtils.base64ToByte(base64));
                    if (bufferedImage == null) {
                        content = content.replaceAll("\\{\\{image_src" + index + "}}", "");
                    } else {
                        int height = bufferedImage.getHeight();
                        int width = bufferedImage.getWidth();
                        // 如果图片宽度小于600,则图片不缩放,还是使用原图片
                        if (width > 600) {
                            BufferedImage imgZoom = ImageUtils.resizeImage(bufferedImage, 600, height);
                            String imageToBase64 = ImageUtils.imageToBase64(ImageUtils.imageToBytes(imgZoom));
                            content = content.replaceAll("\\{\\{image_src" + index + "}}", prefix + imageToBase64);
                        } else {
                            content = content.replaceAll("\\{\\{image_src" + index + "}}", prefix + base64);
                        }
                    }
                } else {
                    content = content.replaceAll("\\{\\{image_src" + index + "}}", "");
                }
                index++;
            }
            // 执行导出操作
            WordUtil.exportHtmlToWord(request, response, content, "富文本内容导出word");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
